package com.example.guoxun.livewallpagerdemo;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.common.transparent.module.CameraPreviewView;

/**
 * 在MIUI中，不能通过"个性主题"找到我们注册的动态壁纸
 */
public class MainActivity extends AppCompatActivity {

    public static final int CODE_REQUEST_CAMERA = 0;

    TextView mLaunchWallpager;
    CameraPreviewView mCameraPreviewView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        if (hasWallpaperPermission()) {
            startWallpager();
            mCameraPreviewView.startPreview();
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    private void initView() {
        mLaunchWallpager = (TextView) findViewById(R.id.launch_wallpaper);
        mCameraPreviewView = (CameraPreviewView) findViewById(R.id.camera_preview_view);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case CODE_REQUEST_CAMERA: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mCameraPreviewView.startPreview();
                    startWallpager();
                }
            }
        }
    }


    /**
     * 启动壁纸
     */
    private void startWallpager() {
        Intent intent = new Intent(Intent.ACTION_SET_WALLPAPER);
        startActivity(intent);
    }

    private boolean hasWallpaperPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA}, CODE_REQUEST_CAMERA);
            return false;
        }
        return true;
    }
}
